from fastapi import APIRouter, Depends, HTTPException, UploadFile, File
from sqlalchemy.orm import Session
from typing import List
import os
import shutil
from ..deps import get_db, get_current_user
from ...models.user import User
from ...schemas.user import User as UserSchema
from fastapi.responses import FileResponse

router = APIRouter()

UPLOAD_DIR = "uploads/avatars"
os.makedirs(UPLOAD_DIR, exist_ok=True)

@router.post("/avatar", response_model=UserSchema)
async def upload_avatar(
    file: UploadFile = File(...),
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    # 确保文件是图片
    if not file.content_type.startswith('image/'):
        raise HTTPException(status_code=400, detail="File must be an image")
    
    # 生成唯一的文件名
    file_extension = os.path.splitext(file.filename)[1]
    filename = f"{current_user.id}{file_extension}"
    file_path = os.path.join(UPLOAD_DIR, filename)
    
    # 保存文件
    with open(file_path, "wb") as buffer:
        shutil.copyfileobj(file.file, buffer)
    
    # 更新用户头像路径
    current_user.avatar = f"/api/avatars/{filename}"
    db.commit()
    db.refresh(current_user)
    
    return current_user

@router.get("/avatar/{filename}")
async def get_avatar(filename: str):
    file_path = os.path.join(UPLOAD_DIR, filename)
    if not os.path.exists(file_path):
        raise HTTPException(status_code=404, detail="Avatar not found")
    return FileResponse(file_path) 